package com.kuanter.kuanterauto.dataservices;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.activity.MyMessageActivity;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.db.DBManager;
import com.kuanter.kuanterauto.entity.MessageInfo;
import com.kuanter.kuanterauto.entity.MessageInfoList;
import com.kuanter.kuanterauto.main.HomeActivityGroup;
import com.kuanter.kuanterauto.main.MainActivity;
import com.kuanter.kuanterauto.main.UpdateReceive;
import com.kuanter.kuanterauto.net.HttpUtil;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
/**
 * 推送服务
 * @author soup
 *
 */
public class PushServices extends Service {	// implements Runnable
	
	public static boolean isRun=false;
	private Thread thread=null;
	private int notAlert=0;
	private String houre="";
	public static List<MessageInfo> messageInfos=null;
	
	//通知
	NotificationManager notificationManager=null;
	 Notification notification=null;
	 
	 DBManager dbManager;
	 
	 public static int unReadMessage = 0;
	 
	 AlarmManager am;
	
	@Override
	public void onCreate() {
		dbManager = new DBManager(this);
		
//		am = (AlarmManager)getSystemService(ALARM_SERVICE);
//		Intent update = new Intent(this, UpdateReceive.class);
//		update.setAction("com.update.Ad");
//		PendingIntent intent = PendingIntent.getBroadcast(this, 100, update, PendingIntent.FLAG_UPDATE_CURRENT);
//		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60*1000, intent);  //24*60*  
		
		System.out.println("create service remote!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		notificationManager=(NotificationManager)this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		// 定义Notification的各种属性   
         notification =new Notification(R.drawable.ic_launcher, "宽途汽车", System.currentTimeMillis()); 
        notification.defaults=Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        
		isRun=true;
		Log.i("aaa", thread + "---");
		if(thread==null){
//			thread=new Thread(this);
			thread = new Thread(getMessage);
			thread.start();
		}
		
		super.onCreate();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		System.out.println("start service remote!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		/*System.out.println("start service");
		notificationManager=(NotificationManager)this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		// 定义Notification的各种属性   
         notification =new Notification(R.drawable.ic_launcher, "宽途汽车", System.currentTimeMillis()); 
        notification.defaults=Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
        */
		super.onStart(intent, startId);
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	
	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}
	
	@Override
	public void onDestroy() {
		isRun=false;
		if(thread!=null){
			thread.interrupt();
			thread=null;
		}
		super.onDestroy();
		Log.i("ccc", "destorty");
//		Intent intent = new Intent(this, PushServices.class);
//		startService(intent);
	}

	Runnable getMessage = new Runnable() {
	
	
	@Override
	public void run() {
		while(isRun){
			try {//60*60*1000 
				Thread.sleep(60*60*1000);//
			}  catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			//TODO
			/*houre=StringUtils.getTime(System.currentTimeMillis());
			String h[]=houre.split(":");
			SharedPreferences s = getSharedPreferences("userinfo", MODE_PRIVATE);
			notAlert=s.getInt("notAlert", 0);
			if(notAlert==1){
				if(!h[0].equals("21")&&!h[0].equals("22")&&!h[0].equals("23")&&!h[0].equals("00")&&!houre.equals("01")&&!h[0].equals("02")
						&&!h[0].equals("03")&&!h[0].equals("04")&&!h[0].equals("05")&&!h[0].equals("06")&&!h[0].equals("07")&&!h[0].equals("08")){
					System.out.println(h[0]);
					List<NameValuePair> params=new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("deviceToken", MainActivity.Token));
					String result=HttpUtil.requestStringForPost(MainConstants.HOST+"query_unRead_message",params);
					System.out.println(result);
					try {
						if(StringUtils.isSuccess(result)){
							if(messageInfos!=null){
								messageInfos.clear();
								messageInfos=null;
							}
							MessageInfoList msgList=new MessageInfoList(result);
							messageInfos=msgList.getMessageInfos();
							if(messageInfos!=null){
								notification();
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}else{
				List<NameValuePair> params=new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("deviceToken", MainActivity.Token));
				String result=HttpUtil.requestStringForPost1(MainConstants.HOST+"query_unRead_message",params);
				try {
					if(StringUtils.isSuccess(result)){
						if(messageInfos!=null){
							messageInfos.clear();
							messageInfos=null;
						}
						MessageInfoList msgList=new MessageInfoList(result);
						messageInfos=msgList.getMessageInfos();
						if(messageInfos!=null){
							notification();
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}*/
			//TODO
			
			boolean push = SharePrefenceUtil.getMessagePush(PushServices.this);
			if (push) {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("deviceToken",
						MainActivity.Token));
				/*params.add(new BasicNameValuePair("notAlert",
						"1"));*/
				String result = HttpUtil.requestStringForPost1(
						MainConstants.HOST_test + "query_unRead_message", params);
				try {
					if (StringUtils.isSuccess(result)) {
						if (messageInfos != null) {
							messageInfos.clear();
							messageInfos = null;
						}
						MessageInfoList msgList = new MessageInfoList(result);
						messageInfos = msgList.getMessageInfos();
						//TODO
						/*MessageInfo info = new MessageInfo();
						info.setContent("GNU是自由软件之父 Richard Stallman在1984年组织开发的一个完全基于自由软件的软件体系，与此相应的有一分通用公共许可证(General Public License，简称GPL)。Linux以及与她有关的大量软件是在GPL的推动下开发和发布的自由软件之父 Stallman像一个神态庄严的传教士一样喋喋不休地到处传播自由软件的福音，阐述他创立GNU的梦想：“自由的思想，而不是免费的午餐”。这位自由软件的“顶级神甫”为自己的梦想付出了大半生的努力，他不但自己创作了许多自由软件如GCC和GDB");
						info.setPushTime(new Date().toLocaleString());
						info.setTitle("GNU是自由软件");
						messageInfos = new ArrayList<MessageInfo>();
						messageInfos.add(info);*/
						//TODO
						
						if (messageInfos != null) {
							unReadMessage = unReadMessage + messageInfos.size();
							dbManager.add(messageInfos);
							dbManager.closeDB();
							notification();
							Intent intent = new Intent(HomeActivityGroup.show_action);
							intent.putExtra("status", HomeActivityGroup.show);
							sendBroadcast(intent);
							
							Intent set_intent = new Intent("com.setting.show");
							sendBroadcast(set_intent);
							
							Log.i("aaa", "发送消息");
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			/*try {//60*60*1000
				Thread.sleep(60*60*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}*/

		}
	}
	
	};
	
	public static List<MessageInfo> getmessageInfos(){
		return messageInfos;
	}
	
	
	
	private void notification(){
		CharSequence contentTitle ="消息"; // 通知栏标题   
        CharSequence contentText ="您有" + unReadMessage + "条未读新的消息"; // 通知栏内容   
        
        Intent notificationIntent =new Intent(getApplicationContext(), MyMessageActivity.class); // 点击该通知后要跳转的Activity
//        notificationIntent.setAction(MainConstants.PUSH_ACTION);
        
        SharedPreferences sp = getSharedPreferences("push", MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putBoolean("push", true);
		editor.commit();
//        notificationIntent.putExtra("PUSH", true);
        PendingIntent contentItent = PendingIntent.getActivity(this, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT );   //
        notification.setLatestEventInfo(this, contentTitle, contentText, contentItent);   
        // 把Notification传递给NotificationManager   
        notificationManager.notify(0, notification); 
        
        System.out.println(StringUtils.getTime(System.currentTimeMillis()));
	}
	


}
